import { loginOut, getUserMenu, getUserPermissionMenu } from '@/api/user'
import { getToken,
  setToken,
  removeToken,
  getAuditStatus,
  setAuditStatus,
  removeAuditStatus,
  getWxCode,
  setWxCode
} from '@/utils/auth'
import router, { resetRouter } from '@/router'
// import { identity, education, randomString } from '@/utils'
const state = {
  token: getToken(),
  auditStatus: getAuditStatus() || '0',
  userInfo: localStorage.getItem('userInfo'),
  businessInfo: JSON.parse(localStorage.getItem('businessInfo')),
  name: localStorage.getItem('businessName'), // 机构名字
  avatar: localStorage.getItem('logo'),
  businessId: localStorage.getItem('businessId'),
  businessLat: localStorage.getItem('businessLat'),
  businessLng: localStorage.getItem('businessLng'),
  identity: null, // 用户身份
  education: null, // 学历
  introduction: '',
  roles: [],
  openId: '',
  unionId: '',
  accessToken: '',
  wxUserInfo: JSON.parse(localStorage.getItem('wxUserInfo')) || {},
  wxCode: getWxCode() || ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_AUDITSTATUS: (state, auditStatus) => {
    state.auditStatus = auditStatus
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_BUSSINESSINFO: (state, businessInfo) => {
    state.businessInfo = businessInfo
  },
  SET_BUSSINESSId: (state, businessId) => {
    state.businessId = businessId
  },
  SET_BUSSINESSLAT: (state, businessLat) => {
    state.businessLat = businessLat
  },
  SET_BUSSINESSLNG: (state, businessLng) => {
    state.businessLng = businessLng
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_OPENId: (state, openId) => {
    state.openId = openId
  },
  SET_UNIONID: (state, unionId) => {
    state.unionId = unionId
  },
  SET_ACCESSTOKEN: (state, accessToken) => {
    state.accessToken = accessToken
  },
  SET_WXCODE: (state, wxCode) => {
    state.wxCode = wxCode
  },
  SET_WXUSERINFO: (state, wxUserInfo) => {
    state.wxUserInfo = wxUserInfo
  }
}

const actions = {
  setwxCode({ commit }, code) {
    commit('SET_WXCODE', code)
    setWxCode(code)
  },
  setwxUserInfo({ commit }, wxUserInfo) {
    commit('SET_WXUSERINFO', wxUserInfo)
  },
  removewxUserInfo({ commit }) {
    commit('SET_WXUSERINFO', {})
    localStorage.removeItem('wxUserInfo')
  },
  // user login
  login({ commit }, data) {
    // const { username, password } = userInfo
    return new Promise(async(resolve, reject) => {
      // userInfo.identity = data.userInfo && identity(data.userInfo.identity)
      // userInfo.education = data.userInfo && education(data.userInfo.education)
      // const roles = permissionList && permissionList.map(i => {
      //   return {
      //     name: i.name,
      //     url: i.url
      //   }
      // })
      commit('SET_TOKEN', data.token)
      commit('SET_USERINFO', data.userInfo || {})
      // commit('SET_ROLES', permissionList)
      commit('SET_AUDITSTATUS', JSON.stringify(data.auditStatus) || '0')
      setToken(data.token)
      setAuditStatus(JSON.stringify(data.auditStatus) || '0')

      // localStorage.setItem('roles', JSON.stringify(roles))
      commit('SET_USERINFO', data.userInfo || {})
      localStorage.setItem('userInfo', JSON.stringify(data.userInfo || {}))
      resolve(data)
    })
  },
  wxLogin({ commit }, data) {
    const { openId, unionId, accessToken } = data
    commit('SET_OPENId', openId)
    commit('SET_UNIONID', unionId)
    commit('SET_ACCESSTOKEN', accessToken)
  },
  // set roles
  setRoles({ commit, state }, roles) {
    commit('SET_ROLES', roles)
  },
  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      const roles = localStorage.getItem('roles')
      commit('SET_ROLES', JSON.parse(roles))
      resolve(JSON.parse(roles))
    })
  },
  setBusinessInfo({ commit }, businessInfo) {

  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      loginOut({ 'x-access-token': state.token }).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_AUDITSTATUS', '0')
        removeToken()
        removeAuditStatus()
        localStorage.clear()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_AUDITSTATUS', '0')
      removeToken()
      removeAuditStatus()
      localStorage.clear()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, businessInfo) {
    return new Promise(async(resolve, reject) => {
      localStorage.setItem('businessId', businessInfo.businessId)
      localStorage.setItem('businessName', businessInfo.businessName)
      localStorage.setItem('businessLat', businessInfo.lat)
      localStorage.setItem('businessLng', businessInfo.lng)
      localStorage.setItem('businessInfo', JSON.stringify(businessInfo))
      localStorage.setItem('logo', businessInfo.logo)
      commit('SET_NAME', businessInfo.businessName)
      commit('SET_AVATAR', businessInfo.logo)
      commit('SET_BUSSINESSId', businessInfo.businessId)
      commit('SET_BUSSINESSLAT', businessInfo.lat)
      commit('SET_BUSSINESSLNG', businessInfo.lng)
      commit('SET_BUSSINESSINFO', businessInfo || {})
      // const { data } = await getUserMenu({
      //   'userId': JSON.parse(localStorage.getItem('userInfo')).id,
      //   'orgId': businessInfo.businessId
      // })
      const { data } = await getUserPermissionMenu({
        'userId': JSON.parse(localStorage.getItem('userInfo')).id,
        'orgId': businessInfo.businessId
      })
      resetRouter()
      const roles = data || []
      // console.log(roles, 'roles')

      commit('SET_ROLES', roles)
      localStorage.setItem('roles', JSON.stringify(roles))
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
      router.addRoutes(accessRoutes)
      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
